﻿using com.uplus.common;
using com.uplus.data;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebApi.Models;

namespace WebApi.Bill.Biz
{
    public class BizUser : BizBase
    {
        readonly string tb = "UserModel";
        readonly string pk = "userID";

        #region 添加
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(UserModel model)
        {
            model.userID = Guid.NewGuid().ToString("N");
            model.tRegister = DateTime.Now;
            return Da.InsertModel<UserModel>(model);
        }

        public int AddModel(UserModel model)
        {
            model.tRegister = DateTime.Now;
            return Da.InsertModel<UserModel>(model);
        }
        #endregion

        #region 更新
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Update(UserModel model)
        {
            model.tRegister = DateTime.Now;
            return Da.UpdateModel(model);
        }
        #endregion

         
        #region GetList
        /// <summary>
        /// 获取信息列表
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable GetList(string sql)
        {
            return Da.GetList(sql);
        }

        public List<UserModel> GetListBySql(string sql)
        {
            return Da.GetModelList<UserModel>(sql);
        }

        public List<UserModel> GetListModel()
        {
            return Da.GetModelList<UserModel>();
        }
        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="pageNum">当前页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="recordCount">总列数</param>
        /// <returns></returns>
        public List<UserModel> GetPageList(dynamic data, ref int recordCount, ref int totalPage)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"select * from {this.tb} where 1=1 ");
            JObject joFilters = FiltersSql.GetQueryCond(data);
            sb.Append(joFilters["sqlAppend"].ToString());
            sb.Append($" order by tRegister desc");
            int pageNum = Convert.ToInt32(joFilters["pageNum"]);
            int pageSize = Convert.ToInt32(joFilters["pageSize"]);
            return Da.PageList<UserModel>(sb.ToString(), pageNum, pageSize, ref recordCount, ref totalPage);
        }
        #endregion

        #region Get
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public UserModel Get(string code)
        {
            return Da.GetModel<UserModel>(x => x.userID == code);
        }

        public UserModel GetModelByNameAndPassWord(string userName, string userPwd)
        {
            return Da.GetModel<UserModel>(x => x.userName == userName&&x.userPwd == userPwd);
        }

        #endregion

        #region Delete 
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public int Delete(string code)
        {
            return Da.Delete(this.tb, this.pk, code);
        }
        #endregion


        #region 生成token
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public dynamic GetToken(UserModel info)
        {
            //JObject response = new JObject();
            //response.Add("Status", true);
            //response.Add("Token", CreateToken(info));
            //response.Add("Type", "Bearer");
            //response.Add("LoginName", info.UserName);
            return CreateToken(info);
        }
        public string CreateToken(UserModel info)
        {
            //创建用户身份标识，可按需要添加更多信息
            var claims = new Claim[]
            {
                new Claim("UserID", Convert.ToString(info.userID), ClaimValueTypes.String), // 用户id
                new Claim("UserName", info.userName==null?"":info.userName, ClaimValueTypes.String), // 用户名
                new Claim("IdCard", info.idCard==null?"":info.idCard,ClaimValueTypes.String), // 卡号
                new Claim("PhoneNumber", info.phonenumber==null?"":info.phonenumber,ClaimValueTypes.String), // 电话号码
                new Claim("NickName", info.nickName==null?"":info.nickName, ClaimValueTypes.String), // 昵称
                new Claim("UserPwd", info.userPwd==null?"":info.userPwd,ClaimValueTypes.String), // 密码
                new Claim("Sex", info.sex==null?"":info.sex,ClaimValueTypes.String), // 姓名
                new Claim("Email", info.email==null?"":info.email,ClaimValueTypes.String), // 邮件
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppConfigurtaion.GetSecondSection("JwtSetting", "SecurityKey")));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //创建令牌
            var token = new JwtSecurityToken(
              issuer: AppConfigurtaion.GetSecondSection("JwtSetting", "Issuer"),
              audience: AppConfigurtaion.GetSecondSection("JwtSetting", "Audience"),
              signingCredentials: credentials,
              claims: claims,
              notBefore: DateTime.Now,
              expires: DateTime.Now.AddSeconds(Convert.ToDouble(AppConfigurtaion.GetSecondSection("JwtSetting", "ExpireSeconds")))
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
        #endregion

        #region 初始化用户信息
        /// <summary>
        /// 初始化用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="isAdmin"></param>
        /// <param name="cust"></param>
        /// <returns></returns>
        LoginInfoModel Init(DmRecord cust)
        {
            LoginInfoModel loginModel = new LoginInfoModel();
            Dictionary<string, object> user = new Dictionary<string, object>();
            loginModel.CustCode = cust.ToString("pkCode");
            loginModel.CompanyName = cust.ToString("sName");
            loginModel.AreaNum = cust.ToString("sAreaNum");
            loginModel.Areas = cust.ToString("sAreas");
            loginModel.Types = cust.ToString("sTypes");
            loginModel.Guid = cust.ToString("sGuid");
            loginModel.UserAction = cust.ToString("UserAction");
            loginModel.IsMagazine = cust.To<bool>("isMagazine", false);
            loginModel.IsMixedFunction = cust.To<bool>("isMixedFunction", false);
            loginModel.CompanyShortName = cust.ToString("sShortName");
            loginModel.Functions = cust.ToString("sFunctions");
            loginModel.WebsiteTitle = cust.ToString("sWebsiteTitle");
            loginModel.WebsiteBotton = cust.ToString("sWebsiteBotton");
            return loginModel;
        }
        #endregion


    }
}
